<?php
namespace org\kahikai\database\mysql;

require_once dirname(__FILE__) . '/../DevelopmentDao.php';
require_once dirname(__FILE__) . '/../PictureDao.php';
require_once dirname(__FILE__) . '/KahikaiMysql.php';
require_once dirname(__FILE__) . '/../../domain/DevelopmentStep.php';

use org\kahikai\database\DevelopmentDao;
use org\kahikai\database\PictureDao;
use org\kahikai\domain\DevelopmentStep;

/**
 * 
 * @author ch4mp
 *
 */
class MysqlDevelopmentDao implements DevelopmentDao {
	private $pictureDao;
	
	public function __construct(PictureDao $aPictureDao) {
		$this->pictureDao = $aPictureDao;
	}
	
	/**
	 * 
	 * @param int $speciesId a Species id
	 * @return the first DevelopmentStep for provided Species or null
	 */
	public function getBySpeciesId($speciesId) {
		$steps = array();
		$map = array();
		$pics = $this->pictureDao->getBySpeciesId($speciesId);
		
		$result = KahikaiMysql::query("SELECT s.id, s.name, s.major, c.prev_step_id FROM DEVELOPMENT_STEP s, DEVELOPMENT_CHAIN c WHERE s.id=c.step_id AND c.species_id=$speciesId");
		while($record = $result->fetch_assoc()) {
			$step = new DevelopmentStep($record['id'], $record['name'], $record['major']);
			if(isset($pics[$record['id']])) {
				$step->picture = $pics[$record['id']];
			}
			$steps[$record['id']] = $step;
			if(isset($record['prev_step_id'])) {
				$map[$record['id']] = $record['prev_step_id'];
			} else {
				$firstId = $record['id'];
			}
		}
		$result->close();
		
		foreach($map as $stepId => $prevId) {
			$steps[$stepId]->previous = $steps[$prevId];
			$steps[$prevId]->next = $steps[$stepId];
		}
		
		if(isset($firstId)) {
			return $steps[$firstId];
		} else {
			return null;
		}
	}
}